<template>
  <div class="route-detail">
    <el-card class="route-info-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="card-title">工艺信息</span>
          <div class="header-buttons">
            <el-button type="primary" :icon="EditPen" @click="handleEdit" v-if="!isReadonly">编辑</el-button>
            <el-button @click="goBack">返回</el-button>
          </div>
        </div>
      </template>

      <el-descriptions :column="2" border>
        <el-descriptions-item label="工艺编码">{{ routeInfo.routeCode }}</el-descriptions-item>
        <el-descriptions-item label="工艺名称">{{ routeInfo.routeName }}</el-descriptions-item>
        <el-descriptions-item label="工艺类型">
          <el-tag :type="getTypeColor(routeInfo.routeType)">{{ getTypeText(routeInfo.routeType) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="版本号">{{ routeInfo.version }}</el-descriptions-item>
        <el-descriptions-item label="工艺状态">
          <el-tag :type="getStatusType(routeInfo.status)">{{ getStatusText(routeInfo.status) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建人">{{ routeInfo.createdBy }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ routeInfo.createdTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ routeInfo.updatedTime }}</el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">{{ routeInfo.description || "暂无描述" }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card class="route-steps-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="card-title">工艺步骤</span>
          <div class="header-buttons">
            <el-button type="primary" :icon="CirclePlus" @click="handleAddStep" v-if="canEditSteps">添加步骤</el-button>
          </div>
        </div>
      </template>

      <el-table :data="stepList" style="width: 100%" border>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="stepOrder" label="步骤顺序" width="100" />
        <el-table-column prop="stepCode" label="步骤编码" />
        <el-table-column prop="stepName" label="步骤名称" />
        <el-table-column prop="workstationCode" label="工作站" />
        <el-table-column prop="qualityCheckRequired" label="质检要求" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.qualityCheckRequired ? 'success' : 'info'">
              {{ scope.row.qualityCheckRequired ? "需要" : "不需要" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" v-if="canEditSteps">
          <template #default="scope">
            <el-button type="primary" link @click="handleEditStep(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="handleRemoveStep(scope.row)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 工艺表单抽屉 -->
    <RouteForm ref="formDrawerRef" />
  </div>
</template>

<script setup lang="ts" name="RouteDetail">
import { ref, reactive, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { EditPen, CirclePlus } from "@element-plus/icons-vue";
import RouteForm from "./form.vue";
import { getRouteById, removeRouteStep, type Route } from "@/api/modules/route";

const route = useRoute();
const router = useRouter();

const routeId = ref<number>(Number(route.params.id));
const routeInfo = ref<Route.RouteListItem>({} as Route.RouteListItem);
const stepList = ref<any[]>([]);
const loading = ref(false);

// 计算是否为只读模式
const isReadonly = computed(() => {
  return ["published", "archived"].includes(routeInfo.value.status);
});

// 计算是否可以编辑步骤
const canEditSteps = computed(() => {
  return ["created", "enabled"].includes(routeInfo.value.status);
});

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    created: "info",
    enabled: "success",
    disabled: "warning",
    published: "primary",
    archived: "info"
  };
  return statusMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    created: "已创建",
    enabled: "已启用",
    disabled: "已禁用",
    published: "已发布",
    archived: "已归档"
  };
  return statusMap[status] || status;
};

// 获取类型颜色
const getTypeColor = (type: string) => {
  const typeMap: Record<string, string> = {
    PRODUCTION: "primary",
    INSPECTION: "warning",
    PACKAGING: "success"
  };
  return typeMap[type] || "info";
};

// 获取类型文本
const getTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    PRODUCTION: "生产",
    INSPECTION: "检测",
    PACKAGING: "包装"
  };
  return typeMap[type] || type;
};

// 获取工艺详情
const getRouteDetail = async () => {
  loading.value = true;
  try {
    const res = await getRouteById(routeId.value);
    routeInfo.value = res.data;

    // TODO: 获取步骤列表，这里需要根据实际API调整
    // const stepsRes = await getRouteSteps(routeId.value);
    // stepList.value = stepsRes.data;
  } catch (error) {
    console.error("获取工艺详情失败:", error);
    ElMessage.error("获取工艺详情失败");
  } finally {
    loading.value = false;
  }
};

// 工艺表单抽屉引用
const formDrawerRef = ref<InstanceType<typeof RouteForm>>();

// 编辑工艺
const handleEdit = () => {
  const params = {
    title: "编辑",
    isView: false,
    row: { ...routeInfo.value },
    getTableList: getRouteDetail
  };
  formDrawerRef.value?.open(params);
};

// 添加步骤
const handleAddStep = () => {
  // TODO: 实现添加步骤逻辑
  ElMessage.info("添加步骤功能待实现");
};

// 编辑步骤
const handleEditStep = (step: any) => {
  // TODO: 实现编辑步骤逻辑
  ElMessage.info("编辑步骤功能待实现");
};

// 移除步骤
const handleRemoveStep = async (step: any) => {
  ElMessageBox.confirm(`确认移除步骤 "${step.stepName}" 吗？`, "移除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        await removeRouteStep(routeId.value, { stepId: step.id });
        ElMessage.success("步骤移除成功");
        getRouteDetail();
      } catch (error) {
        console.error("步骤移除失败:", error);
        ElMessage.error("步骤移除失败");
      }
    })
    .catch(() => {
      // 取消移除
    });
};

// 返回
const goBack = () => {
  router.back();
};

// 页面加载时获取数据
onMounted(() => {
  getRouteDetail();
});
</script>

<style scoped>
.route-detail {
  padding: 20px;
}

.route-info-card,
.route-steps-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
}

:deep(.el-table__row) {
  height: 30px !important;
  line-height: 35px;
}

:deep(.el-table__cell) {
  padding: 12px 0;
}
</style>